package com.zhanglinwei.openApiClient.segment;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Getter
@Setter
public class HavingSegment implements SQLSegment{

    private final List<String> havingSegmentList = new ArrayList<>();

    @Override
    public boolean isEmpty() {
        return CollectionUtils.isEmpty(havingSegmentList);
    }

    public void removeLastIf(Predicate<String> condition) {
        if (isEmpty()) {
            return;
        }

        int lastIndex = havingSegmentList.size() - 1;
        String lastElement = havingSegmentList.get(lastIndex);

        if (condition == null || condition.test(lastElement)) {
            havingSegmentList.remove(lastIndex);
        }
    }

    public void removeLastLogicOperator() {
        removeLastIf(item -> item.equals(SQLKeyword.AND.sqlSegment()) || item.equals(SQLKeyword.OR.sqlSegment()));
    }

    public void addAll(WhereSegment whereSegment) {
        if (whereSegment == null || whereSegment.isEmpty()) {
            return;
        }

        this.havingSegmentList.addAll(whereSegment.getWhereSegmentList());
    }

    @Override
    public void add(SQLSegment... sqlSegments) {
        if (ArrayUtils.isNotEmpty(sqlSegments)) {
            Arrays.asList(sqlSegments).forEach(item -> havingSegmentList.add(item.sqlSegment()));
        }
    }

    @Override
    public String sqlSegment() {
        return SQLKeyword.HAVING.sqlSegment() + " " + String.join(" ", havingSegmentList);
    }

}
